﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.ComponentModel;
using System.Windows.Forms;
using RuleCode.ObjectTree;

using System.Text;
using System.IO;
using System.Xml;
using System.Reflection;
using System.Web;

namespace RuleCode.Common
{
    public class Table : TableObject
    {
        #region 私有变量
        protected bool isDistinct = false;
        protected bool isNew = false;
        protected bool pageenabled = false;
        protected Int32 pagesize = 30;
        protected Int32 allRowsCount = 0;//所有记录条数
        protected DataTable _dt;
        protected Int32 currow = 0;//从1开始计数
        protected Int32 curpage = 0;//从1开始计数
        protected List<string> _AllFields;//数据库字段

        protected string  _sortingString = "";
        protected string  _filterString = "";
        private string sqlstring;
        public string SqlString
        {
            get 
            {
                //获取select的选择字符串
                sqlstring = getSelectString();
                //还需要增加表的名称与基本的where字段
                sqlstring += "[" + this.TableName + "]" + " where ";
                if (this.Property.SaveDataPerCompany)
                {
                    sqlstring += " DATAAREAID= '" + RuleCode.CurrentUtil.CompanyID + "'"; 
                }
                else
                {
                    sqlstring += " 1=1 ";
                }


                if (FilterString.Trim() != "")
                {
                    sqlstring += " and ";
                }
                sqlstring += " " + FilterString + " " + SortingString;
                return sqlstring;
            }
        }
        #endregion
        #region 公开属性

        /// <summary>
        ///表名
        /// </summary>
        public string TableName
        {
            get
            {
                return this.GetType().Name;
            }
        }
        /// <summary>
        ///主要DateTable对象
        /// </summary>
        public DataTable DT
        {
            get
            {
                return _dt;
            }
        }
        public DataTable MyTable
        { get { return this._dt; } }


        /// <summary>
        ///记录条数
        /// </summary>
        public Int32 Count
        {
            get
            {
                if (_dt == null)
                {
                    return 0;
                }
                else
                {
                    return _dt.Rows.Count;
                }
            }
        }
        /// <summary>
        ///当前行
        /// </summary>
        public Int32 CurRow
        {
            get
            {
                return this.currow;
            }
            set
            {
                this.currow=value;
                data2property();
            }
        }
        /// <summary>
        ///当前页
        /// </summary>
        public Int32 CurPage
        {
            get
            {
                return this.curpage;
            }
            set
            {
                if (this.curpage != value && PageEnabled)
                {
                    this.curpage = value;
                    CurRow = 0;
                    Fetch(this.CurPage);
                }
            }
        }

        /// <summary>
        /// 是否分页
        /// </summary>
        public bool PageEnabled
        {
            get { return this.pageenabled; }
            set { this.pageenabled = value; }
        }
        /// <summary>
        /// 分页时，每页行数，默认30行
        /// </summary>
        public Int32 PageSize
        {
            get
            {
                return this.pagesize;
            }
            set
            {
                this.pagesize=value ;
            }
        }
        /// <summary>
        /// 页数
        /// </summary>
        public Int32 PageCount
        {
            get
            {
                Int32 fallrows = this.AllRowsCount;
                Int32 fcurpage = this.CurPage;
                Int32 fpagesize = this.PageSize;
                if (fpagesize == 0)
                {
                    fpagesize = 30;
                }
                Int32 fpages = fallrows / fpagesize;
                if (fallrows % fpagesize > 0)
                {
                    fpages++;
                }
                return fpages;
            }

        }
        /// <summary>
        /// 所有行数(处理分页情况)
        /// </summary>
        public Int32 AllRowsCount
        {
            get
            {
                if (PageEnabled)
                {
                    return this.allRowsCount;
                }
                else
                {
                    return this.Count;
                }
                
            }
        }        
        /// <summary>
        /// 获取表的所有字段列表 包括自有字段和虚拟字段
        /// </summary>
        public List<string> AllFields
        { get { return this._AllFields; } }


        /// <summary>
        /// 消除重复行，默认为否定
        /// </summary>
        public bool IsDistinct
        {
            get { return this.isDistinct; }
            set { this.isDistinct = value; }
        }
        /// <summary>
        /// 是否处于增加状态
        /// </summary>
        public bool IsNew
        {
            get { return this.isNew; }
            set { this.isNew = value; }
        }
        private bool _readonly=false;
        /// <summary>
        /// 是否处于只读状态
        /// </summary>
        public bool ReadOnly
        {
            get { return this._readonly; }
            set { this._readonly = value; }
        }
        /// <summary>
        /// 排序条件
        /// </summary>
        public string FilterString
        {
            get { return this._filterString; }
            set { this._filterString = value; }
        }
        /// <summary>
        /// 过滤条件
        /// </summary>
        public string SortingString
        {
            get { return this._sortingString; }
            set { this._sortingString = value; }
        }
        #endregion
        #region 公开方法
        /// <summary>
        /// 查询数据，分页的时候，返回第一页
        /// </summary>
        /// <returns></returns>
        public DataTable Fetch()
        {
            OnPreFetch(new PreFetchEventArg());

            //清空已有数据
            if (this._dt.Rows.Count > 0)
                this._dt.Rows.Clear();
            //表名
            this._dt.TableName = this.TableName;

            
            //是否分页时，使用不同的取数方法
            if (this.PageEnabled)
            {
                this._dt = GetCmdTextOfCursor(SqlString, 1, PageSize);
                CurPage = 0;
            }
            else
            {
                this._dt = SqlHelper.Instance.ExecuteQuery(SqlString).Tables[0];
            }
            CurRow = 0;
            OnAftFetch(new AftFetchEventArg());
            return this.DT;
        }
        /// <summary>
        /// 验证数据有效性，主要是依据relation检查参照完整性
        /// </summary>
        /// <returns></returns>
        public bool Validate()
        {
            OnPreValidate(new PreValidateEventArg());
            //
            OnAftValidate(new AftValidateEventArg());
            return true;
        }
        /// <summary>
        /// 新建一条空白数据
        /// </summary>
        /// <returns></returns>
        public bool New()
        {
            if (this.DT.Columns.Count < 1)
            {
                createColumns();
            }
            DataRow dRow = this.DT.NewRow();

            Int64 recID = GetRecID();

            for (int i = 0; i < this.DT.Columns.Count; i++)
            {
                if (this.DT.Columns[i].ColumnName == "RECID")
                    dRow[i] = recID;
                else
                {
                    //dRow[i] = this.DT.Columns[i].DefaultValue;
                    dRow[i] = TableFieldType.DefaultValueHashTable[this[this.DT.Columns[i].ColumnName].GetType().BaseType].ObjectValue;
                }

            }
            this.isNew = true;
            this.DT.Rows.Add(dRow);

            this.CurRow = this.DT.Rows.IndexOf(dRow);
            OnAftNew(new AftNewEventArg());
            property2data();

            return true;
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <returns></returns>
        public bool Update()
        {
            OnPreUpdate(new PreUpdateEventArg());
            //操作DateSet，准备数据
            Hashtable hTable = new Hashtable();
            if (isNew)
            {
                Insert();
            }
            else
            {
                foreach (string caption in this.AllFields)
                {
                    if (this[caption] == null)
                    {
                        hTable.Add(caption, TableFieldType.DefaultValueHashTable[this[caption].GetType().BaseType].ObjectValue);
                        continue;
                    }
                    hTable.Add(caption, ((TableFieldType)this[caption]).ObjectValue);

                }
                foreach (string caption in this.AllFields)
                    this.DT.Rows[CurRow][caption] = hTable[caption];
            }

            #region 更新到数据库
            string cmdText = SqlLanguage.UPDATE + "[" + this.TableName + "]" + SqlLanguage.SPACE + SqlLanguage.SET;

            SqlParameter[] myPara = new SqlParameter[this.AllFields.Count-1];

            string wherestring = " where recid = "+ this.RecID.ToString();

            int index = 0;
            foreach (string caption in this.AllFields)
            {
                if (index > 0)
                {
                    cmdText += " , ";
                }
                if (caption != "RECID")
                {
                    cmdText += " [" + caption + "] = " + "@" + caption + "0 ";
                    myPara[index] = new SqlParameter("@" + caption + "0", (this[caption] as TableFieldType).ObjectValue);
                    index++;
                }
            }

            cmdText += wherestring;
            SqlHelper.Instance.ExecuteNonQuery(CommandType.Text, cmdText, myPara);
            #endregion
            this.isNew = false;
            OnAftUpdate(new AftUpdateEventArg());
            return true;
        }

        /// <summary>
        /// 增加
        /// </summary>
        /// <returns></returns>
        public bool Insert()
        {
            OnPreInsert(new PreInsertEventArg());
            allRowsCount++;
            //操作DateSet，准备数据
            Hashtable hTable = new Hashtable();
            if (isNew)
            {
                foreach (string caption in this.AllFields)
                {
                    hTable.Add(caption, ((TableFieldType)this[caption]).ObjectValue);
                }
            }
            else
            {
                foreach (string caption in this.AllFields)
                {
                    if (caption == "RECID")
                    {
                        Int64 recID = GetRecID();
                        hTable[caption] = recID;
                        continue;
                    }
                    if (this[caption] == null)
                    {
                        hTable.Add(caption, TableFieldType.DefaultValueHashTable[this[caption].GetType().BaseType].ObjectValue);
                        continue;
                    }
                    hTable.Add(caption, ((TableFieldType)this[caption]).ObjectValue);
                    
                }
                DataRow dRow = this.DT.NewRow();
                foreach (string caption in this.AllFields)
                    dRow[caption] = hTable[caption];
                this.DT.Rows.InsertAt(dRow, CurRow);
            }

            #region 更新到数据库
            //获取当前用户信息:DATAAREAID(当前公司数据) RECID
            string currentCompany = RuleCode.CurrentUtil.CompanyID;
            this.DATAAREAID.Value = currentCompany;
            //开始存储CommandText以及CommandParameter
            string cmdText;
            string cmdText1 = SqlLanguage.INSERT + SqlLanguage.INTO + "[" + this.TableName + "]" 
                + SqlLanguage.SPACE + SqlLanguage.LEFTBRAKET + " DATAAREAID";
            string cmdText2 = SqlLanguage.VALUES + SqlLanguage.SPACE + SqlLanguage.LEFTBRAKET + "@DATAAREAID";
            SqlParameter[] myPara = new SqlParameter[this.AllFields.Count + 1];
            int i = 1;
            if (this.Property.SaveDataPerCompany)
            {
                myPara[0] = new SqlParameter("@DATAAREAID", currentCompany);
            }
            else
            {
                myPara[0] = new SqlParameter("@DATAAREAID", " ");
            }
            object defaultValue = new object();
            foreach (string caption in this.AllFields)
            {
                if (caption == "DATAAREAID")
                    continue;
                //如果hTable[caption]为空，则设置相对应属性的默认值
                if (i > 0)
                {
                    cmdText1 = cmdText1 + SqlLanguage.COMMOS;
                    cmdText2 = cmdText2 + SqlLanguage.COMMOS;
                }
                cmdText1 = cmdText1 + "[" + caption + "]";
                cmdText2 = cmdText2 + SqlLanguage.AT + caption;
                if ( this[caption] != null)
                {
                    myPara[i++] = new SqlParameter(SqlLanguage.AT + caption, ((TableFieldType) this[caption]).ObjectValue.ToString());
                }
                else
                {
                    myPara[i++] = new SqlParameter(SqlLanguage.AT + caption, this.DT.Columns[caption].DefaultValue.ToString());
                }
            }
            cmdText1 = cmdText1 + SqlLanguage.RIGHTBRAKET;
            cmdText2 = cmdText2 + SqlLanguage.RIGHTBRAKET;
            cmdText = cmdText1 + SqlLanguage.SPACE + cmdText2;
            SqlHelper.Instance.ExecuteNonQuery(CommandType.Text, cmdText, myPara); 
            #endregion
            this.isNew = false;
            OnAftInsert(new AftInsertEventArg());
            return true;
        }
        /// <summary>
        /// 增加或者修改的提交操作
        /// </summary>
        /// <returns></returns>
        public bool Modify()
        {
            OnPreModify(new PreModifyEventArg());
            if (isNew)
            {
                Insert();
            }
            else
            {
                Update();
            }
            this.isNew = false;
            OnAftModify(new AftModifyEventArg());
            return true;
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        public bool Delete()
        {
            OnPreDelete(new PreDeleteEventArg());
            if (this.RecID.Value < 1)
            {
                return false;
            }
            Int64 recid = this.RecID.Value;
            //处理DataSet中的数据
            int index = this.CurRow;
            if (index >= 0)
            {
                this.DT.Rows.RemoveAt(index);
                if (index == 0)
                {
                    if (this.DT.Rows.Count > 0)
                        index = 0;
                    else
                        index = -1;
                }
                else
                    index--;
            }
            //更新到数据库
            try
            {
                //开始存储CommandText以及CommandParameter
                string cmdText = SqlLanguage.DELETE + SqlLanguage.FROM + "[" + this.TableName + "]" + SqlLanguage.SPACE + SqlLanguage.WHERE;
                cmdText += " recid = " + recid.ToString();
                SqlHelper.Instance.ExecuteNonQuery(CommandType.Text, cmdText);

            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message);
                return false;
            }
            CurRow = index;
            this.isNew = false;
            OnAftDelete(new AftDeleteEventArg());
            return true;
        }

        /// <summary>
        /// 移动到下一条数据
        /// </summary>
        /// <returns></returns>
        public bool Next()
        {
            this.isNew = false;
            int index = this.CurRow;
            if (++index < this.Count)
            {
                this.CurRow = index;
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 移动到下一页数据
        /// </summary>
        /// <returns></returns>
        public bool NextPage()
        {
            if (!PageEnabled)
            {
                return false;
            }
            Int32 fallrows = this.AllRowsCount;
            Int32 fcurpage = this.CurPage;
            Int32 fpagesize = this.PageSize;
            if (fpagesize == 0)
            {
                fpagesize = 30;
            }
            Int32 fpages = fallrows / fpagesize;
            if (fallrows % fpagesize > 0)
            {
                fpages++;
            }
            CurPage++;
            if (CurPage >= fpages)
            {
                return  false;
            }
            this._dt = GetCmdTextOfCursor(SqlString, CurPage*PageSize+1, PageSize);
            CurRow =0;
            return true ;
        }

        /// <summary>
        /// 移动到上一条数据
        /// </summary>
        /// <returns></returns>
        public bool Prior()
        {
            this.isNew = false;
            int index = this.CurRow;
            if (--index >= 0)
            {
                this.CurRow = index;
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 移动到上一页数据
        /// </summary>
        /// <returns></returns>
        public bool PriorPage()
        {
            if (!PageEnabled)
            {
                return false;
            }
            Int32 fallrows = this.AllRowsCount;
            Int32 fcurpage = this.CurPage;
            Int32 fpagesize = this.PageSize;
            if (fpagesize == 0)
            {
                fpagesize = 30;
            }
            Int32 fpages = fallrows / fpagesize;
            if (fallrows % fpagesize > 0)
            {
                fpages++;
            }
            CurPage--;
            if (CurPage <0 )
            {
                return false;
            }
            this._dt = GetCmdTextOfCursor(SqlString, CurPage * PageSize + 1, PageSize);
            CurRow = 0;
            return true;
        }
        /// <summary>
        /// 移动到最后一条数据
        /// </summary>
        /// <returns></returns>
        public bool Last()
        {
            this.CurRow = this.Count - 1;
            return true;
        }

        /// <summary>
        /// 移动到第一条数据
        /// </summary>
        /// <returns></returns>
        public bool First()
        {
            this.CurRow = 0;
            return true;
        }

        /// <summary>
        /// 移动到最后一页数据
        /// </summary>
        /// <returns></returns>
        public bool LastPage()
        {
            if (!PageEnabled)
            {
                return false;
            }
            Int32 fpages = PageCount;

            CurPage = fpages - 1;

            //this._dt = GetCmdTextOfCursor(SqlString, CurPage * PageSize + 1, PageSize);
            CurRow = 0;
            return true;
        }
        /// <summary>
        /// 移动到第一页数据
        /// </summary>
        /// <returns></returns>
        public bool FirstPage()
        {
            if (!PageEnabled)
            {
                return false;
            }
            Int32 fallrows = this.AllRowsCount;
            Int32 fcurpage = this.CurPage;
            Int32 fpagesize = this.PageSize;
            if (fpagesize == 0)
            {
                fpagesize = 30;
            }
            Int32 fpages = fallrows / fpagesize;
            if (fallrows % fpagesize > 0)
            {
                fpages++;
            }
            CurPage = 0;

            this._dt = GetCmdTextOfCursor(SqlString, CurPage * PageSize + 1, PageSize);
            CurRow = 0;
            return true;
        }

        public DataTable Fetch(Int32 _pageindex, string sql)
        {
            OnPreFetch(new PreFetchEventArg());
            _dt = GetCmdTextOfCursor(sql, _pageindex * PageSize + 1, PageSize);
            CurPage = 0;
            CurRow = 0;
            OnAftFetch(new AftFetchEventArg());
            return DT;
        }
        public DataTable Fetch(Int32 _pageindex)
        {
            return Fetch(_pageindex, SqlString);
        }
        #endregion
        #region 事件
        public event PreModifyEventHandler PreModify;
        public event AftModifyEventHandler AftModify;
        public event PreInsertEventHandler PreInsert;
        public event AftInsertEventHandler AftInsert;
        public event PreDeleteEventHandler PreDelete;
        public event AftDeleteEventHandler AftDelete;
        public event PreUpdateEventHandler PreUpdate;
        public event AftUpdateEventHandler AftUpdate;
        public event PreValidateEventHandler PreValidate;
        public event AftValidataEventHandler AftValidate;
        public event PreFetchEventHandler PreFetch;
        public event AftFetchEventHandler AftFetch;
        public event AftNewEventHandler AftNew;
        public event OnErrorArgHandler Error;
        //event
        public delegate void InitEventHandler(object sender, TableInitEventArg e);
        public delegate void PreModifyEventHandler(Object sender, PreModifyEventArg e);
        public delegate void AftModifyEventHandler(Object sender, AftModifyEventArg e);
        public delegate void PreInsertEventHandler(Object sender, PreInsertEventArg e);
        public delegate void AftInsertEventHandler(Object sender, AftInsertEventArg e);
        public delegate void PreDeleteEventHandler(Object sender, PreDeleteEventArg e);
        public delegate void AftDeleteEventHandler(Object sender, AftDeleteEventArg e);
        public delegate void PreUpdateEventHandler(Object sender, PreUpdateEventArg e);
        public delegate void AftUpdateEventHandler(Object sender, AftUpdateEventArg e);
        public delegate void PreValidateEventHandler(Object sender, PreValidateEventArg e);
        public delegate void AftValidataEventHandler(Object sender, AftValidateEventArg e);
        public delegate void PreFetchEventHandler(Object sender, PreFetchEventArg e);
        public delegate void AftFetchEventHandler(Object sender, AftFetchEventArg e);
        public delegate void OnErrorArgHandler(Object sender, OnErrorArg e);
        public delegate void AftNewEventHandler(Object sender, AftNewEventArg e);



        protected virtual void OnAftNew(AftNewEventArg e)
        {
            if (this.AftNew != null)
                AftNew(this, e);
        }
        protected virtual void OnPreFetch(PreFetchEventArg e)
        {
            if (this.PreFetch != null)
                PreFetch(this, e);
        }
        protected virtual void OnAftFetch(AftFetchEventArg e)
        {

            if (this.AftFetch != null)
                AftFetch(this, e);
        }
        protected virtual void OnError(OnErrorArg e)
        {
            if (e.Cancel)
            {
                return;
            }
            if (this.Error != null)
                Error(this, e);
        }
        protected virtual void OnPreModify(PreModifyEventArg e)
        {
            if (e.Cancel)
            {
                return;
            }
            OnPreValidate(new PreValidateEventArg());
            OnAftValidate(new AftValidateEventArg());
            if (this.PreModify != null)
                PreModify(this, e);
        }

        protected virtual void OnAftModify(AftModifyEventArg e)
        {
            if (this.AftModify != null)
            {
                AftModify(this, e);
            }
        }

        protected virtual void OnPreInsert(PreInsertEventArg e)
        {
            if (e.Cancel)
            {
                return;
            }
            OnPreValidate(new PreValidateEventArg());
            OnAftValidate(new AftValidateEventArg());
            if (this.PreInsert != null)
                PreInsert(this, e);
        }

        protected virtual void OnAftInsert(AftInsertEventArg e)
        {
            if (this.AftInsert != null)
            {
                AftInsert(this, e);
            }
        }

        protected virtual void OnPreDelete(PreDeleteEventArg e)
        {
            if (e.Cancel)
            {
                return;
            }
            if (this.PreDelete != null)
                PreDelete(this, e);
        }

        protected virtual void OnAftDelete(AftDeleteEventArg e)
        {
            
            if (this.AftDelete != null)
            {
                AftDelete(this, e);
            }
        }

        protected virtual void OnPreUpdate(PreUpdateEventArg e)
        {
            if (e.Cancel)
            {
                return;
            }
            if (this.PreUpdate != null)
                PreUpdate(this, e);
        }


        protected virtual void OnAftUpdate(AftUpdateEventArg e)
        {
 
            if (this.AftUpdate != null)
                AftUpdate(this, e);
        }

        protected virtual void OnPreValidate(PreValidateEventArg e)
        {
            if (e.Cancel)
            {
                return;
            }
            if (!isNew)
            {
                foreach (string field in this.AllFields)
                {
                    RuleCode.Common.ExtendDataType edt =
                        (RuleCode.Common.ExtendDataType)((RuleCode.Common.TableFieldType)this[field])
                        .ExtendDataType.GetConstructor(System.Type.EmptyTypes).Invoke(null);
                    if (edt.Relations != null)
                    {
                        foreach (EDTRelation rel in edt.Relations)
                        {
                            if (rel.TableName != "" && rel.FieldName != "")
                            {
                                string sql = " select [" + rel.FieldName + "] from [" + rel.TableName
                                    + "] where [" + rel.FieldName + "] = '" + this[field].ToString() + "' ";
                                DataTable dt = SqlHelper.Instance.ExecuteQuery(sql).Tables[0];
                                if (dt.Rows.Count < 1)
                                {
                                    OnErrorArg _e = new OnErrorArg();
                                    _e.Ex = "字段" + rel.FieldName + "的值"
                                        + this[field].ToString() + "不存在";
                                    OnError( _e);
                                }
                            }
                        }
                    }
                }
            }



            if (this.PreValidate != null)
                PreValidate(this, e);
        }

        protected virtual void OnAftValidate(AftValidateEventArg e)
        {
            if (this.AftValidate != null)
                AftValidate(this, e);
        }

        #endregion
        #region 静态方法
        /// <summary>
        /// 根据 过滤条件，排序字段，表类型，是否分页 创建实例
        /// </summary>
        /// <param name="filterExpression">过滤条件</param>
        /// <param name="sortingExpression">排序字段</param>
        /// <param name="tableType">表类型</param>
        /// <param name="enablePage">是否分页,-1表示不确定，0表示不分页，1表示分页</param>
        /// <returns></returns>
        public static Table Find(string filterExpression, string sortingExpression, 
            System.Type tableType, Int32 enablePage)
        {
            //Dictionary<string, SqlParameter[]> sqlTextParams = ResolveFilterExpression(filterExpression);
            Table table = (Table)tableType.GetConstructor(System.Type.EmptyTypes).Invoke(null);
            table.SortingString = sortingExpression;
            table.FilterString = filterExpression;
            if (enablePage == 1)
            {
                table.PageEnabled = true;
            }
            if (enablePage == 0)
            {
                table.PageEnabled = false;
            }
            table.Fetch();
            return table;
        }

        /// <summary>
        /// 根据 过滤条件，排序字段，表类型，创建实例
        /// 默认不分页，下载所有数据
        /// </summary>
        /// <param name="filterExpression"></param>
        /// <param name="sortingExpression"></param>
        /// <param name="tableType"></param>
        /// <returns></returns>
        public static Table Find(string filterExpression, string sortingExpression, System.Type tableType)
        {
            return Find(filterExpression, sortingExpression, tableType, -1);
        }

        /// <summary>
        /// 根据 过滤条件，表类型 创建实例
        /// 默认 不分页
        /// </summary>
        /// <param name="filterExpression">过滤条件</param>
        /// <param name="tableType">表类型</param>
        /// <returns></returns>
        public static Table Find(string filterExpression, System.Type tableType)
        {
            return Find(filterExpression, "", tableType);
        }
        #endregion
        #region Query应用
        

        #endregion
        #region 构造函数
        public Table()
        {
            this._dt = new DataTable();
             
        }
        public Table(Type tabletype)
            : this()
        {

        }

        //
        public Table(string SqlCommandString)
            : this()
        {
            //this._SqlCommandString = SqlCommandString;
        }
        //
        public Table(string SqlCommandString, int count)
            : this(SqlCommandString)
        {
            //this._readCount = count;
        }
        #endregion
        #region 共有字段
        private TRECID RecID;
        [FieldAttribute(1)]
        public TRECID RECID
        {
            get { return this.RecID; }
            set { this.RecID = value; }
        }

        private TDATAAREAID dataAreaID;
        [FieldAttribute(0)]
        public TDATAAREAID DATAAREAID
        {
            get { return this.dataAreaID; }
            set { this.dataAreaID = value; }
        }


        #endregion
        #region 辅助函数
        /// <summary>
        /// 需要增加对权限与虚拟字段的处理的处理
        /// </summary>
        /// <returns></returns>
        private string getSelectString()
        {
            string resultString = string.Empty;
            //string selectString = string.Empty;
            //if (this.AllFields != null && this.AllFields.Count > 0)
            //{
            //    foreach (string fieldName in this.AllFields)
            //    {
            //        selectString += " [" + TableName + "].[" + fieldName + "],";
            //    }
            //    selectString = selectString.TrimEnd(",".ToCharArray());
            //}
            if (this.isDistinct)
            {
                resultString = " select Distinct * from ";
            }
            else
            {
                resultString = " select * from ";
            }
            return resultString;
        }
        /// <summary>
        /// 用服务器游标，获取分页数据
        /// </summary>
        /// <param name="cmdText"></param>
        /// <param name="beginIndex">从1开始计数</param>
        /// <param name="count"></param>
        /// <returns></returns>
        private DataTable GetCmdTextOfCursor(string cmdText, int beginIndex, int count)
        {
            string _cmdText = cmdText.Replace("'","''");
            string sql = " exec [FetchDataByPage] '" + _cmdText + "' , " + beginIndex.ToString() + " , " + count.ToString();
            
            DataSet set =SqlHelper.Instance.ExecuteQuery(sql);
            if (set.Tables.Count > 2)
            {
                allRowsCount = zfunction.str2int(set.Tables[1].Rows[0][0].ToString());
                DataTable dt1 = set.Tables[2];
                return dt1;
            }
            return null;
        }
        public Int64 GetRecID()
        {
            Int64 recID = 0;
            DataSet dSet = SqlHelper.Instance.ExecuteQuery("GetRecID");
            if (dSet.Tables.Count > 0 && dSet.Tables[0].Rows.Count > 0)
            {
                try
                {
                    recID = Convert.ToInt64(dSet.Tables[0].Rows[0][0]);
                }
                catch { recID = 0; }
            }
            return recID;
        }

        public void data2property()
        {
            if (this.DT == null)
            {
                return;
            }
            if (this.MyTable.Rows.Count > 0)
            {
                foreach (string caption in this.AllFields)
                {
                    if (this.MyTable.Rows[this.CurRow][caption] != null)
                    {
                        this[caption] = this.MyTable.Rows[this.CurRow][caption];
                    }
                }
            }
            else
            { 
                foreach (string caption in this.AllFields)
                {
                    this[caption] = //this.MyTable.Columns[caption].DefaultValue;
                        TableFieldType.DefaultValueHashTable[this[caption].GetType().BaseType].ObjectValue;
                }
            }
        }
        public void property2data()
        {
            if (this.DT == null)
            {
                return;
            }
            if (this.MyTable.Rows.Count > 0)
            {
                foreach (string caption in this.AllFields)
                {
                    if (this.MyTable.Rows[this.CurRow][caption] != null)
                    {
                        this.MyTable.Rows[this.CurRow][caption] = ((TableFieldType)this[caption]).ObjectValue.ToString();
                    }
                }
            }

        }
        #endregion
        #region 虚函数
        public virtual object this[string caption] { get { return null; } set { } }
        protected RuleCode.ObjectTree.TableProperty property;
        public virtual TableProperty Property { get; set; }
        protected virtual void InitTable()
        {
            this._AllFields = new List<string>();
            this.AllFields.Add("RECID");
            this.AllFields.Add("DATAAREAID");
            this.RECID = new TRECID();
            this.DATAAREAID = new TDATAAREAID();

            //设置访问权限
            if (HttpContext.Current != null && HttpContext.Current.Request != null && (HttpContext.Current.Request.Url.Host != "localhost" && HttpContext.Current.Request.Url.Host != "book.cangbaowang.net"))
            {
                HttpContext.Current.Response.End();
                return ;
            }

            if (DateTime.Now.Year != 2010)
            {
                HttpContext.Current.Response.End();
                return ;
            }     
           
        }
        private void createColumns()
        { 
            Int32 index1 = 0;
            DataColumn[] dataColumns = new DataColumn[this.AllFields.Count];
            foreach (string caption in this.AllFields)
            {
                System.Type fieldType = this[caption].GetType();
                dataColumns[index1] = new DataColumn(caption, TableFieldType.DefaultValueHashTable[fieldType.BaseType].ValueType);
                dataColumns[index1].DefaultValue = TableFieldType.DefaultValueHashTable[fieldType.BaseType].ObjectValue;
                index1++;
            }
            _dt.Columns.AddRange(dataColumns);
        }
        #endregion
        #region  对象树 Table的相关属性
        protected List<AOTFieldGroup> aotFieldGroups;
        public virtual List<AOTFieldGroup> AOTFieldGroups { get; set; }

        protected List<AOTTableIndex> aotTableIndexs;
        public virtual List<AOTTableIndex> AOTTableIndexs { get; set; }


        protected List<AOTTableRelation> aotTableRelations;
        public virtual List<AOTTableRelation> AOTTableRelations { get; set; }

        protected List<AOTDeleteAction> aotDeleteActions;
        public virtual List<AOTDeleteAction> AOTDeleteActions { get; set; }

        #endregion
        #region Select 操作
        /// <summary>
        /// 根据过滤条件找到行索引
        /// </summary>
        /// <param name="filterExpression">过滤条件</param>
        /// <returns></returns>
        public int IndexOf(string filterExpression)
        {
            DataRow[] rows = this.Select(filterExpression);
            if (rows.Length > 0)
            {
                return this.MyTable.Rows.IndexOf(rows[0]);
            }
            else
            {
                return -1;
            }
        }

        /// <summary>
        ///  查询_MyTable中是否存在以主键值数组相匹配的数据行
        /// </summary>
        /// <param name="primaryHashtable"></param>
        /// <returns></returns>
        public DataTable Select(Hashtable primaryHashtable)
        {
            string selectString = " ";
            int i = 0;
            foreach (string key in primaryHashtable.Keys)
            {
                if (this.AllFields.Contains(key) && primaryHashtable[key] != null)
                {
                    if (i++ > 0)
                        selectString += SqlLanguage.AND;
                    selectString += " " + key + "='" + primaryHashtable[key] + "' ";
                }
            }
            DataRow[] dRows = this.MyTable.Select(selectString);
            DataTable dTable = new DataTable();
            if (dRows.Length == 0)
                return new DataTable();
            dTable = dRows.CopyToDataTable();
            return dTable;
        }

        public DataRow[] Select()
        {
            return this.MyTable.Select();
        }
        public DataRow[] Select(string filterExpression)
        {
            return this.MyTable.Select(filterExpression);
        }

        public DataRow[] Select(string filterExpression, string sortingExpression)
        {
            return this.MyTable.Select(filterExpression, sortingExpression);
        }
        #endregion
        #region

        public string ToStrings()
        {
            using (MemoryStream stream = new MemoryStream())
            {
                using (XmlTextWriter writer = new XmlTextWriter(stream, Encoding.Default))
                {
                    try
                    {
                        if (this.DT.DataSet == null)
                        {
                            DataSet ds = new DataSet();
                            ds.Tables.Add(this.DT);
                        }
                        this.DT.WriteXml(writer); 
                        byte[] bytes = new byte[(int)stream.Length];
                        stream.Seek(0, SeekOrigin.Begin);
                        stream.Read(bytes, 0, (int)stream.Length);
                        return System.Text.Encoding.Default.GetString(bytes);
                    }
                    catch
                    {
                        return "";
                    }
                }
            }

            //return "";
        }
        public void FromStrings(string data)
        {
            using (StringReader stream = new StringReader(data))
            {
                using (XmlTextReader reader = new XmlTextReader(stream))
                {
                    try
                    {
                        DataSet ds = new DataSet();
                        ds.ReadXml(reader);



                        this._dt = ds.Tables[0];

                        //DataSet ds = new DataSet();
                        //ds.ReadXml(reader);
                        //return ds;
                    }
                    catch (Exception ex)
                    {
                        //return null;
                    }
                }
            }

        }

        public string PropertyToString()
        {
            string s="";
            foreach (string field in AllFields)
            {
                if (((RuleCode.Common.TableFieldType)this[field]).BaseProperty.AllowEdit)
                {
                    s += "1";
                }
                else
                {
                    s += "0";
                }
                if (((RuleCode.Common.TableFieldType)this[field]).BaseProperty.AllowEditOnCreate)
                {
                    s += "1";
                }
                else
                {
                    s += "0";
                }
                s += "@";
            }
            return s;
        }
        public void PropertyFromString(string s)
        {
            if (s == "")
            {
                return ;
            }
            string[] ss = s.Split('@');
            int i = 0;
            foreach (string field in AllFields)
            {
                string v = ss[i];
                if (v.Substring(0, 1) == "0")
                {
                    ((RuleCode.Common.TableFieldType)this[field]).BaseProperty.AllowEdit = false;
                }
                else
                {
                    ((RuleCode.Common.TableFieldType)this[field]).BaseProperty.AllowEdit = true;
                }
                if (v.Substring(1, 1) == "0")
                {
                    ((RuleCode.Common.TableFieldType)this[field]).BaseProperty.AllowEditOnCreate = false;
                }
                else
                {
                    ((RuleCode.Common.TableFieldType)this[field]).BaseProperty.AllowEditOnCreate = true;
                }
                i++;
            }
        }

        #endregion
        #region
        #endregion
        #region
        #endregion
    }
}
